<?php
class Log{
	protected $loadedXmlFile;
	protected $logFile;
	protected $exceplog;
	
	public function __construct(){
		if (file_exists('config/xml/system.xml')){
			$this->loadedXmlFile=simplexml_load_file('config/xml/system.xml');
		}
	}
	/**
	 * write system log
	 *
	 * @param string $string
	 */
	public function write($string){
		date_default_timezone_set("Asia/shanghai");
		$nowDate = date("Y-m-d H:i:s");
		$string = "#".$nowDate.":".$string."\r\n";
		if ($this->logFile=="") {
			$this->loadLogFile();
		}
		$log = $this->logFile;
		try {
			$resource = fopen($log,"a+");
			fwrite($resource,$string);
			fclose($resource);
		}catch (Exception $e){
			$this->writeExcepLog($e);
		}
	}
	/**
	 * write Exception log
	 * 
	 *
	 * @param string $string sentence
	 * @return null
	 */
	public function writeExcepLog($string){
		date_default_timezone_set("Asia/shanghai");
		$nowDate = date("Y-m-d H:i:s");
		$string = "#".$nowDate.":".$string."\r\n";
		if ($this->exceplog==""){
			$this->loadExceptionLog();
		}
		$exceplog = $this->exceplog;
		try {
			$resource = fopen($exceplog,"a+");
			fwrite($resource,$string);
			fclose($resource);
		}catch (Exception $e){
			return "";
		}
	}
	/**
	 * load log file name from the system config
	 *
	 * @return string log file path
	 */
	public function loadLogFile(){
		if ($this->loadedXmlFile==""){
			if (file_exists('system.xml'))
				$this->loadedXmlFile = simplexml_load_file('system.xml');
			else if (file_exists('config/xml/system.xml'))
				$this->loadedXmlFile = simplexml_load_file('system.xml');
		}
		$configxml = $this->loadedXmlFile;
		$file = (string)$configxml->log->systemlog;
		$this->logFile = $file;
		return $file;
	}
	/**
	 * load exception log file path
	 *
	 * @return string  $file exception log file path
	 */
	public function loadExceptionLog(){
		if ($this->loadedXmlFile==""){
			if (file_exists('system.xml'))
				$this->loadedXmlFile = simplexml_load_file('system.xml');
			else if (file_exists('config/xml/system.xml'))
				$this->loadedXmlFile = simplexml_load_file('system.xml');
		}
		$configxml = $this->loadedXmlFile;
		$file = (string)$configxml->log->exceptionlog;
		$this->exceplog = $file;
		return $file;
	}
	function xmlTest(){
		$xml = simplexml_load_file('system.xml');
		//$xml->log[1]->addChild("date","2010-3-4");
		//$xml->log[1]->addChild("date","2009-3-4");
		$xmlstr = $xml->asXML();
		$file = fopen('system.xml',w);
		fwrite($file,$xmlstr);
		fclose($file);
	}
}

?>